﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//添加额外引用
using System.Data.Sql;
using System.Diagnostics;
using System.Data.SqlClient;
using Mmht.BT;
using System.IO;

public partial class admin_phsj_drsj : System.Web.UI.Page
{
    UploadExcel ue = new UploadExcel();
    //文件路径
    private string filepath;
    string sheetname;
    DataTable dt = new DataTable();
    int create_by;
    string dirp = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        dirp = Server.MapPath("files/download/temp");
        if (Session["admin_id"] == null)
        {
            Response.Redirect("admin_logout.aspx");
            return;
        }
        try
        {
            create_by = (Int32)Session["admin_id"];
        }
        catch
        {
            create_by = 2;
        }
        
        if (!IsPostBack)
        {
            //数据表格隐藏
            DataHide();
            Mb_Load();
        }
        else
        {

        }
    }

    /// <summary>
    /// 上传选定文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button_upload_click_Click(object sender, EventArgs e)
    {
        string message = GetFilepath();
        //数据文件路径获取
        if (message!="error")
        {
            //Ecxel数据显示
            DataShow();
            //Excel数据读取
            GetSheet();
        }
        else
        {
            //Excel数据隐藏
            DataHide();
        }

    }

    /// <summary>
    /// 取得文件路径
    /// </summary>
    /// <returns></returns>
    protected string GetFilepath()
    {
        string FileName = "";
        //文件路径获取
        FileName = FileUpload1.FileName;

        if (FileName == "" || FileName == null)
        {
            //文件不存在，提示上传文件
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "更新提示", "<script language='javascript'>  warning('请先选择一个excel文件，然后上传！');</script>");
            return "error";
        }
        else if(!ue.CheckExcel(FileName))
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "更新提示", "<script language='javascript'>  warning('请选择Excel文件上传(.xls)');</script>");
            return "error";
        }
        //文件路径声明
        System.IO.DirectoryInfo path = new DirectoryInfo(Server.MapPath("~/files/temp/"));
        //删除当前路径的所有Excel文件，避免文件冲突
        deletefile(path);
        //文件路径赋值
        filepath = path + FileName;
        ViewState["filepath"] = filepath;
        try
        {
            //文件存储在服务器上
            if (filepath == null)
                filepath = ViewState["filepath"].ToString();
            FileUpload1.SaveAs(filepath);
            return filepath;
        }
        catch 
        {
            return "error";
        }


        ////////////////////////////////////////////////////
        //解决IOException: 文件“Excel模板.xls”正由另一进程使用，因此该进程无法访问该文件。问题添加
        FileUpload1.PostedFile.InputStream.Close();
        FileUpload1.PostedFile.InputStream.Dispose();
        FileUpload1.Dispose();
        ////////////////////////////////////////////////////
        //if (filepath == null)
        //    filepath = ViewState["filepath"].ToString();

        //文件不存在，提示出错
        if (!System.IO.File.Exists(filepath))
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "更新提示", "<script language='javascript'>  warning('您选择的Excel文件可能不存在！');</script>");
            return "error";
        }
        //文件不是XLS文件，提示出错
        else if (System.IO.Path.GetExtension(filepath).ToUpper().CompareTo(".XLS") != 0)
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "更新提示", "<script language='javascript'>  warning('请选择Excel文件上传(.xls)！');</script>");
            // throw new Exception("请选择或者输入Excel文件(.xls)");
            return "error";
        }
        return filepath;

    }

    /// <summary>
    /// 删除指定路径下的文件
    /// </summary>
    /// <param name="path"></param>
    private void deletefile(System.IO.DirectoryInfo path)
    {
        foreach (System.IO.DirectoryInfo subfile in path.GetDirectories())
        {
            try
            {
                //删除文件
                deletefile(subfile);
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show(ex.ToString());
            }

        }
        foreach (System.IO.FileInfo f in path.GetFiles())
        {
            try
            {
                f.Delete();
            }
            catch
            {

            }

        }
    }

    /// <summary>
    /// 获得文件中存在的全部工作表名
    /// </summary>

    private void GetSheet()
    {
        //下拉菜单清空
        DropDownList1.Items.Clear();
        dt=new DataTable();
        dt = ue.GetSheetsName(filepath);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DropDownList1.Items.Add(dt.Rows[i]["TABLE_NAME"].ToString());
        }
        ExcelDatashow();
    }

    /// <summary>
    /// 显示选定表的数据项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //用户选择下拉菜单中的某张数据表名
        //所选数据表中数据显示
        ExcelDatashow();
    }

    /// <summary>
    /// 待插入数据显示
    /// </summary>
    private void ExcelDatashow()
    {
        sheetname = DropDownList1.SelectedValue;
        ViewState["sheetname"] = DropDownList1.SelectedValue;

        if (filepath == null)
        {
            filepath = ViewState["filepath"].ToString();
        }

        try
        {
            dt = new DataTable();
            //将制定路径的文件中的某个工作簿中的数据转化为datatable格式
            dt = ue.ExcelToDT(filepath, sheetname);
            ViewState["dt"] = dt;
            if (dt == null)
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "更新提示", "<script language='javascript'>  warning('数据表中没有数据，请重新选择数据表！');</script>");
                //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "数据集缺失", "<script language='javascript'>alert('数据表中没有数据，请重新选择数据表！');</script>");
            }
            else
            {
                //数据绑定
                GridView1.DataSource = dt;
                //数据显示
                GridView1.DataBind();
            }

        }
        catch (Exception ex)
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "test2", "<script language='javascript'>alert('wahh" + ex.Message + "');</script>");

        }
    }


   
    /// <summary>
    /// 导入数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        string message = string.Empty;
        dt = (DataTable)ViewState["dt"];
        sheetname = ViewState["sheetname"].ToString();
        message = ue.UpdateData(sheetname, dt,create_by);
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "更新提示", "<script language='javascript'>  warning('" + message + "');</script>");

    }

    /// <summary>
    /// 数据显示
    /// </summary>
    /// <param name="ps"></param>
    /// <returns>bool</returns>
    bool DataShow()
    {
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "hyy", "<script language='javascript'>datashow();</script>");
        return true;
    }

    /// <summary>
    /// 数据隐藏
    /// </summary>
    /// <param name="ps"></param>
    /// <returns>bool</returns>
    bool DataHide()
    {
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "hyy", "<script language='javascript'>datahide();</script>");
        return false;
    }

    private void Mb_Load()
    {
        DataTable dt_mb = new DataTable();
        DirectoryInfo mydir = new DirectoryInfo(dirp);
        dt_mb.Columns.Add("id");
        dt_mb.Columns.Add("fn");
        dt_mb.Columns.Add("pth");
        int i = 0;
        foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
        {
            if (fsi is FileInfo)
            {
                FileInfo fi = (FileInfo)fsi;
                string x = System.IO.Path.GetDirectoryName(fi.FullName);
                string s = System.IO.Path.GetExtension(fi.FullName);
                string y = System.IO.Path.GetFileNameWithoutExtension(fi.FullName);
                string fn = y + s;
                if (s == ".xls")
                {
                    try
                    {
                        DataRow dr = dt_mb.NewRow();
                        i++;
                        dr["id"] = i.ToString();
                        dr["fn"] = fn;
                        dr["pth"] = "files/download/temp/" + fn;
                        dt_mb.Rows.Add(dr);
                    }
                    catch
                    {
                    }
                }
            }
        }

        if (dt_mb != null && dt_mb.Rows.Count > 0)
        {
            mb_show_hide(true);
        }
        else
        {
            mb_show_hide(false);
        }
        GridView2.DataSource = dt_mb;
        GridView2.DataBind();
        
    }


    /// <summary>
    /// 删除指定模板
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Bt_del_Click(object sender, EventArgs e)
    {
        string fn = ((Button)sender).CommandArgument.ToString();
        try
        {
            System.IO.File.Delete(dirp + @"\" + fn);
            message_show(fn + "删除成功！");
            Mb_Load();
        }
        catch
        {
            message_show(fn + "删除失败！");
        }
    }



    /// <summary>
    /// 将该模板上传至服务器
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Btmb_Upload_Click(object sender, EventArgs e)
    {
        Mb_Upload();
    }

    /// <summary>
    /// 指定模板上传
    /// </summary>
    private void Mb_Upload()
    {
        
        try
        {
            filepath = ViewState["filepath"].ToString();
        }
        catch
        {
            message_show("上传失败，请检查文件是否有误！");
            return;
        }
        string sj = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
        AdminBT ab = new AdminBT();
        string username = ab.FindbyId(create_by);
        string fn = "材料数据" + "_" + username + "_" + sj + ".xls";
        try
        {
            System.IO.File.Copy(filepath, dirp + @"\" + fn);
            message_show(fn + "已成功上传至服务器！");
            Mb_Load();
        }
        catch
        {
            message_show(fn + "上传失败，请检查文件是否有误！");
        }
    }


    /// <summary>
    /// 信息提示
    /// </summary>
    /// <param name="msg">提示信息</param>
    private void message_show(string msg)
    {
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "信息提示", "<script language='javascript'>  warning('" + msg + "');</script>");
    }

    /// <summary>
    /// 提示
    /// </summary>
    /// <param name="message"></param>
    private void mb_show_hide(bool show)
    {
        if (show)
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", "<script language='javascript'>  mb_show();</script>");
        }
        else
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", "<script language='javascript'>  mb_hide();</script>");
        }
    }
}
